const fs = require('fs')
const path = require('path')
const parser = require('@babel/parser').parse
const traverse = require('@babel/traverse').default
const generate = require('@babel/generator').default
const t = require('@babel/types')

const { _absoluteCwd, getConfig } = require('./getConfigFile')
const config = getConfig('menu')

const setMenuConfig = (
  meta = {
    compName: 'Demo',
    compZhName: '新建Demo',
    compDesc: ''
  }
) => {
  // 要添加的新 navmenu 数据
  const newNavMenuItem = {
    label: '模板',
    icon: '',
    type: 'subMenu',
    subMenuList: [
      {
        label: meta?.compZhName,
        category: 'newCategory',
        type: 'menuItem',
        location: `/${meta?.compName}`,
        permission: ''
      }
    ]
  }

  // 读取目标文件
  const filePath = path.join(_absoluteCwd, config.configFileDir)

  const code = fs.readFileSync(filePath, 'utf-8')

  const ast = parser(code, {
    sourceType: 'module',
    plugins: ['javascript', 'typescript', 'dynamicImport']
  })

  traverse(ast, {
    ExpressionStatement(path) {
      if (
        t.isCallExpression(path.node.expression) &&
        t.isMemberExpression(path.node.expression.callee) &&
        t.isIdentifier(path.node.expression.callee.object, { name: '__registeAppConfig' }) &&
        t.isIdentifier(path.node.expression.callee.property, { name: 'setAppconfig' })
      ) {
        const configObject = path.node.expression.arguments[0]

        if (t.isObjectExpression(configObject)) {
          const navmenuProperty = configObject.properties.find((prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key, { name: 'navmenu' }))

          if (navmenuProperty && t.isArrayExpression(navmenuProperty.value)) {
            const newNavMenuItemObject = t.objectExpression([
              t.objectProperty(t.identifier('label'), t.stringLiteral(newNavMenuItem.label)),
              t.objectProperty(t.identifier('icon'), t.stringLiteral(newNavMenuItem.icon)),
              t.objectProperty(t.identifier('type'), t.stringLiteral(newNavMenuItem.type)),
              t.objectProperty(
                t.identifier('subMenuList'),
                t.arrayExpression(
                  newNavMenuItem.subMenuList.map((subMenuItem) => {
                    return t.objectExpression([
                      t.objectProperty(t.identifier('label'), t.stringLiteral(subMenuItem.label)),
                      t.objectProperty(t.identifier('category'), t.stringLiteral(subMenuItem.category)),
                      t.objectProperty(t.identifier('type'), t.stringLiteral(subMenuItem.type)),
                      t.objectProperty(t.identifier('location'), t.stringLiteral(subMenuItem.location)),
                      t.objectProperty(t.identifier('permission'), t.stringLiteral(subMenuItem.permission))
                    ])
                  })
                )
              )
            ])

            // 将新 navmenu 项添加到 navmenu 数组中
            navmenuProperty.value.elements.push(newNavMenuItemObject)
          }

          const i18nProperty = configObject.properties.find((prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key, { name: 'i18n' }))
          if (i18nProperty && t.isObjectExpression(i18nProperty.value)) {
            // 找到 en 属性
            const enProperty = i18nProperty.value.properties.find((prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key, { name: 'en' }))

            if (enProperty && t.isObjectExpression(enProperty.value)) {
              // 创建新的 i18n 条目
              const newI18nEntryObject = t.objectProperty(t.identifier(meta?.compZhName), t.stringLiteral(meta?.compName))

              // 将新 i18n 条目添加到 en 对象中
              enProperty.value.properties.push(newI18nEntryObject)
            }
          }
        }
      }
    }
  })

  // 生成新代码
  const output = generate(ast, {
    retainLines: true,
    comments: true,
    compact: false,
    jsescOption: { minimal: true } // 确保字符串不被转码为 Unicode 转义序列
  }).code

  // 写回文件
  fs.writeFileSync(filePath, output)

  console.log('navmenu 添加成功！')
}

module.exports = {
  setMenuConfig
}
